<template>
	<!-- <el-dialog title="聊天信息" :visible.sync="visible" width="1100px" top="8vh" class="dialog"> -->
	<div class="wrap" style="height:664px;">
		<!-- <div slot="title" class="title">
			<img :src="IMUser.avatar"  alt="" class="avatar xc-w-50">{{IMUser.nickname}}
		</div> -->
		<div class="block-content">
			<el-menu background-color="#f5f5f5" active-text-color="#18ceb4" :default-active="currentConv" class="tabs"
				@select="selectConv">
				<el-menu-item :index="item.id" v-for="(item, index) in chatList" :key="index">
					<div class="chat-item" slot="title">
						<el-badge :value="item.unread_msg_count" :hidden="item.unread_msg_count === 0" :max="99">
							<img :src="item.avatar || IMUser.avatar" alt="" v-if="item.avatar ||IMUser.avatar">
							<img src="./person_01.png" alt="" v-else>
						</el-badge>
						<div class="title">
							<span>{{item.name}}</span>
							<span v-html="latestMsg(item)"></span>
						</div>
					</div>
				</el-menu-item>
			</el-menu>
			<div class="block-chat">
				<div class="block-record" @scroll="scrollEvent">
					<message :messages="pageMessage" @scroll="recordScroll"></message>
				</div>
				<div class="block-input" v-show="currentConv !== ''">
					<emoji @chooseEmoji="insertEmoji"></emoji>
					<div class="filediv" ref="file1">
						<input type="file" @change="changePic" accept="image/*" name="imgUrls" title="选择图片">
						<img src="./picture.svg" alt="" class="icon-pic">
					</div>
					<div class="editor" contenteditable="true" ref="editor" @keyup="getCursor" @keydown.enter.prevent="submit"
						@paste.prevent="onPaste" @click="getCursor">
					</div>
					<el-button size="mini" class="send" @click="submit()">发送</el-button>
				</div>
			</div>
		</div>

	</div>
	<!-- </el-dialog> -->
</template>

<script>
	// import jxConfig from '../../config'
	import {
		mapGetters
	} from 'vuex'
	import paste from './paste'
	import {
		getCursorPosition,
		setCursorPosition
	} from './cursorPosition'
	import emoji from './emoji'
	import message from './message'
	import {
		Token
	} from '../utils/storage'
	export default {
		name: 'chat',
		descr: '聊天弹框',
		components: {
			emoji,
			message
		},
		data() {
			return {
				visible: false,
				currentConv: '',
				conversation: {},
				cursorPosition: 0,
				page: 1,
				scrollTop: 0,
				chatHistory: []
			}
		},
		computed: {
			...mapGetters({
				conversations: 'conversations',
				IMUser: 'loginUser',
				asyncMessages: 'asyncMessages',
				autoScroll: 'autoScroll'
			}),
			editor() {
				return this.$refs['editor'];
			},
			// 会话列表
			chatList() {
				return this.conversations.map(item => {
					return {
						unread_msg_count: item.unread_msg_count,
						avatar: item.avatar,
						type: item.type,
						name: item.type === 3 ? item.nickName : item.name,
						id: item.type === 3 ? item.username : item.gid
					}
				});
			},
			// 聊天消息
			chatMessages() {
				let message = this.asyncMessages.find(item => {
					if (this.conversation.type === 3) {
						return item.from_username === this.conversation.username;
					} else if (this.conversation.type === 4) {
						return item.from_gid === this.conversation.gid;
					}
					return false
				})
				return message ? message.msgs : []
			},
			// 最新消息
			latestMsg() {
				return function(d) {
					let msg = {};
					if (d.type === 3) {
						msg = this.asyncMessages.find(item => item.from_username === d.id);
					} else if (d.type === 4) {
						msg = this.asyncMessages.find(item => item.from_gid === d.id);
					}
					if (msg === undefined) {
						return '';
					}
					if (msg.msgs && msg.msgs.length > 0) {
						let {
							content
						} = [...msg.msgs].pop();
						switch (content.msg_type) {
							case 'text':
								return content.msg_body.text;
								break;
							case 'file':
								return '[文件]'
								break;
							case 'image':
								return '[图片]'
								break;
							default:
								break;
						}
					} else {
						return '';
					}
				}
			},
			// 分页聊天消息
			pageMessage() {
				let current = this.chatMessages.length - (this.page * 10);
				let start = current >= 0 ? current : 0;
				return this.chatMessages.slice(start);
			},
		},
		methods: {
			// 当前会话
			selectConv(d) {
				if (this.currentConv !== d) {
					this.$store.commit('saveAutoScroll', true);
				}
				this.currentConv = d;
				this.page = 1;
				this.conversation = this.conversations.find(item => item.gid === d || item.username === d);
			},
			recordScroll() {
				var div = document.querySelector('.block-record');
				if (this.autoScroll) {
					div.scrollTop = div.scrollHeight;
				}
			},
			// 聊天消息滚动
			scrollEvent(d) {
				if (d.target.scrollTop === 0) {
					this.$store.commit('saveAutoScroll', false);
					this.page += 1;
				}
				if (d.target.scrollHeight === d.target.scrollTop) {
					this.page = 1;
				}
			},
			// 提交
			submit(e) {
				let el = e ? e.target : this.editor;
				const value = el.innerHTML.replace(/[\n\r]$/, '')
				if (value) {
					// console.info('Submit text', { value })
					this.$store.dispatch('sendMsg', {
						conversation: this.conversation,
						message: value
					});
					el.innerText = ''

				}
			},
			// 粘贴
			async onPaste(e) {
				const result = await paste(e)
				const imgRegx = /^data:image\/png;base64,/
				if (imgRegx.test(result)) {
					document.execCommand('insertImage', false, result)
				} else {
					document.execCommand('insertText', false, result)
				}
			},
			// 获取光标
			getCursor() {
				this.cursorPosition = getCursorPosition(this.editor)
			},
			// 插入emoji
			insertEmoji(emoji) {
				const text = this.editor.innerHTML
				this.editor.innerHTML = text.slice(0, this.cursorPosition) + emoji + text.slice(this.cursorPosition, text.length)
				setCursorPosition(this.editor, this.cursorPosition + 1)
				this.cursorPosition = getCursorPosition(this.editor) + 1 //  emoji takes 2 bytes
			},
			changePic(d) {
				console.log('changePic', d);
				this.$store.dispatch('sendPic', {
					conversation: this.conversation,
					url: this.getObjectURL(d.target.files[0])
				});

			},
			// 获取上传文件的url
			getObjectURL(file) {
				let url = null;
				if (window.createObjectURL != undefined) {
					url = window.createObjectURL(file);
				} else if (window.URL != undefined) {
					url = window.URL.createObjectURL(file);
				} else if (window.webkitURL != undefined) {
					url = window.webkitURL.createObjectURL(file);
				}
				return url;
			}
		},
		mounted() {
			var t = Token.get();
			this.$store.dispatch("loginIM", t);
		},
	}
</script>

<style lang="scss" scoped>
	// 聊天窗样式
	.wrap {
		::v-deep ul {
			list-style: none;
		}

		::v-deep .el-dialog__body {
			background: #f5f5f5;
			padding: 0px;
			height: 650px;

			.tabs {
				width: 310px;
				height: 100%;
				overflow-y: auto;

				&::-webkit-scrollbar {
					width: 4px;
					height: 4px;
				}

				&::-webkit-scrollbar-thumb {
					border-radius: 5px;
					box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.1);
					background: rgba(0, 0, 0, 0.1);
				}

				&::-webkit-scrollbar-track {
					/*滚动条里面轨道*/
					box-shadow: inset 0 0 5px rgba(0, 0, 0, 0);
					border-radius: 0;
					background: no-repeat
				}

				.el-menu-item {
					height: 72px;
					padding: 16px 8px !important;
				}

				.is-active {
					background: rgba(24, 206, 180, 0.1) !important;
					border-left: 3px solid #18ceb4;
				}

				.chat-item {
					height: 100%;
					display: flex;
					flex-direction: row;
					align-items: center;

					img {
						width: 48px;
						height: 48px;
						object-fit: cover;
						border-radius: 4px;
					}

					.title {
						flex: 1;
						display: flex;
						flex-direction: column;
						margin-left: 8px;
						overflow: hidden;

						span {
							overflow: hidden;
							line-clamp: 1;
							text-overflow: ellipsis;
							white-space: nowrap;

							&:first-child {
								line-height: 28px;
							}

							&:last-child {
								height: 20px;
								margin-top: 4px;
								color: #999999;
								font-size: 14px;
								line-height: 20px;
							}
						}
					}
				}
			}

			.block-content {
				display: flex;
				flex-direction: row;
				height: 100%;

				.block-chat {
					flex: 1;
					display: flex;
					flex-direction: column;

					.block-record {
						flex: 1;
						overflow-y: auto;
						scroll-behavior: smooth;

						&::-webkit-scrollbar {
							width: 4px;
							height: 4px;
						}

						&::-webkit-scrollbar-thumb {
							border-radius: 5px;
							box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
							background: rgba(0, 0, 0, 0.2);
						}

						&::-webkit-scrollbar-track {
							/*滚动条里面轨道*/
							box-shadow: inset 0 0 5px rgba(0, 0, 0, 0);
							border-radius: 0;
							background: no-repeat
						}
					}

					.block-input {
						background: #fff;
						border-top: 1px solid #ccc;
						padding: 8px;

						.filediv {
							display: inline-block;
							position: relative;
							top: -24px;
							margin-left: 8px;

							.icon-pic {
								width: 24px;
								position: absolute;
							}

							input {
								position: absolute;
								width: 24px;
								height: 24px;
								opacity: 0;
								z-index: 100;
							}
						}

						.editor {
							height: 80px;
							width: 100%;
							box-sizing: border-box;
							overflow: auto;
							word-break: break-all;
							overflow-wrap: break-word;
							padding: 5px;
							color: black;
							outline: none;

							&::-webkit-scrollbar {
								width: 4px;
								height: 4px;
							}

							&::-webkit-scrollbar-thumb {
								border-radius: 5px;
								box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.1);
								background: rgba(0, 0, 0, 0.1);
							}

							&::-webkit-scrollbar-track {
								/*滚动条里面轨道*/
								box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.0);
								border-radius: 0;
								background: rgba(0, 0, 0, 0.0);
							}
						}

						.send {
							float: right;
							margin-right: 10px;
							margin-top: 4px;

							&:hover,
							&:focus {
								color: #18ceb4;
								background: rgba(24, 206, 180, 0.05);
								border-color: rgba(24, 206, 180, 0.2);
							}

							&:active {
								color: #18ceb4;
								border-color: rgba(24, 206, 180, 0.2);
							}
						}
					}
				}
			}

		}
	}
</style>